package com.tust.androidbbsclient;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Switch;
import android.widget.Toast;

import com.tust.androidbbsclient.domain.User;
import com.tust.androidbbsclient.tool.Application;
import com.tust.androidbbsclient.tool.Tool;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class SettingActivity extends AppCompatActivity {
    Toast toast;
    String Uname, Ugender, Uint, Upasswd;
    int UfavorPrivacy, UcollPrivacy;

    //用于在线程间传递消息
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);//获取子线程传递的消息
            if (msg.what == 1) {//修改用户信息请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("修改用户信息：" + strMsg);

                switch (strMsg) {
                    case "serverFalse":
                        showToast(Tool.addEmoji() + "服务器通信失败！");
                        break;
                    case "databaseFalse":
                        showToast(Tool.addEmoji() + "服务器端错误！");
                        break;
                    case "userExist":
                        showToast(Tool.addEmoji() + "用户已存在！");

                        //返回修改用户信息界面
                        RelativeLayout relativeLayoutNoticeSetting = findViewById(R.id.rl_noticeSetting);
                        RelativeLayout relativeLayoutSetting = findViewById(R.id.rl_setting);
                        ScrollView scrollViewSetting = findViewById(R.id.sv_setting);
                        relativeLayoutNoticeSetting.setVisibility(View.GONE);
                        relativeLayoutSetting.setVisibility(View.VISIBLE);
                        scrollViewSetting.setVisibility(View.VISIBLE);
                        break;
                    case "updateUserFalse":
                        showToast(Tool.addEmoji() + "信息修改失败！");
                        break;
                    case "updateUserSuccess":
                        showToast(Tool.addEmoji() + "信息修改成功！");

                        //跳转活动
                        Intent intent = new Intent(SettingActivity.this, MainActivity.class);
                        intent.putExtra("Uname", Uname);
                        startActivity(intent);
                        overridePendingTransition(R.anim.fade_out, R.anim.fade_in);//改变跳转活动动画，淡出淡入
                        break;
                }
            } else if (msg.what == 2) {//获取用户信息请求返回值
                String strMsg = msg.obj.toString();
                System.out.println("获取用户信息：" + strMsg);

                if (strMsg.equals("serverFalse")) showToast(Tool.addEmoji() + "服务器通信失败！");
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);

        ImageView imageViewSettingBack = this.findViewById(R.id.iv_setting_back);
        Button buttonSaveSetting = this.findViewById(R.id.btn_saveSetting);
        Button buttonSaveSettingConfirm = this.findViewById(R.id.btn_saveSettingConfirm);
        Button buttonSaveSettingCancel = this.findViewById(R.id.btn_saveSettingCancel);
        EditText editTextUnameSetting = this.findViewById(R.id.et_unameSetting);
        EditText editTextetUintSetting = this.findViewById(R.id.et_uintSetting);
        EditText editTextetUpasswdSetting = this.findViewById(R.id.et_upasswdSetting);
        EditText editTextConfirmUpasswdSetting = this.findViewById(R.id.et_confirmUpasswdSetting);
        RadioGroup radioGroupUgenderSetting = this.findViewById(R.id.rg_ugenderSetting);
        RadioButton radioButtonMale = this.findViewById(R.id.rbtn_male);
        RadioButton radioButtonFemale = this.findViewById(R.id.rbtn_female);
        @SuppressLint("UseSwitchCompatOrMaterialCode") Switch switchUfavorPrivacySetting = this.findViewById(R.id.swi_ufavorPrivacySetting);
        @SuppressLint("UseSwitchCompatOrMaterialCode") Switch switchUcollPrivacySetting = this.findViewById(R.id.swi_ucollPrivacySetting);
        RelativeLayout relativeLayoutNoticeSetting = this.findViewById(R.id.rl_noticeSetting);
        RelativeLayout relativeLayoutSetting = this.findViewById(R.id.rl_setting);
        ScrollView scrollViewSetting = this.findViewById(R.id.sv_setting);

        //从Application中获得用户信息，赋给用户信息全局变量
        Application application = (Application) getApplication();
        editTextUnameSetting.setText(application.user.getUname());
        if (application.user.getUgender() != null) {
            if (application.user.getUgender().equals("男")) {
                Ugender = "男";
                radioGroupUgenderSetting.check(radioButtonMale.getId());
            }
            else {
                Ugender = "女";
                radioGroupUgenderSetting.check(radioButtonFemale.getId());
            }
        } else {
            Ugender = "男";
            radioGroupUgenderSetting.check(radioButtonMale.getId());
        }
        editTextetUintSetting.setText(application.user.getUint());
        UfavorPrivacy = application.user.getUfavorPrivacy();
        UcollPrivacy = application.user.getUcollPrivacy();
        switchUfavorPrivacySetting.setChecked(UfavorPrivacy == 0);
        switchUcollPrivacySetting.setChecked(UcollPrivacy == 0);

        //选择按钮组监听事件
        radioGroupUgenderSetting.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton  radioButton = findViewById(radioGroup.getCheckedRadioButtonId());
                Ugender = radioButton.getText().toString();
            }
        });

        //开关按钮监听事件
        switchUfavorPrivacySetting.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) UfavorPrivacy = 0;
                else UfavorPrivacy = 1;
            }
        });

        switchUcollPrivacySetting.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) UcollPrivacy = 0;
                else UcollPrivacy = 1;
            }
        });

        //保存设置按钮监听事件
        buttonSaveSetting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Uname = editTextUnameSetting.getText().toString();
                Uint = editTextetUintSetting.getText().toString();
                Upasswd = editTextetUpasswdSetting.getText().toString();
                String confirmUpasswd = editTextConfirmUpasswdSetting.getText().toString();

                if (Uname.equals("")) showToast(Tool.addEmoji() + "请输入用户名！");
                else if (Uint.equals("")) showToast(Tool.addEmoji() + "请输入个人简介！");
                else if (!(Upasswd.equals("") && confirmUpasswd.equals(""))) {
                    if (!Upasswd.equals(confirmUpasswd)) showToast(Tool.addEmoji() + "密码不一致！");
                    else {
                        relativeLayoutNoticeSetting.setVisibility(View.VISIBLE);
                        relativeLayoutSetting.setVisibility(View.INVISIBLE);
                        scrollViewSetting.setVisibility(View.INVISIBLE);
                    }
                } else {
                    Upasswd = application.user.getUpasswd();

                    relativeLayoutNoticeSetting.setVisibility(View.VISIBLE);
                    relativeLayoutSetting.setVisibility(View.INVISIBLE);
                    scrollViewSetting.setVisibility(View.INVISIBLE);
                }
            }
        });

        //提示弹出框确认按钮监听事件
        buttonSaveSettingConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //发送修改用户信息请求子线程
                new Thread() {
                    @Override
                    public void run() {
                        OutputStream outputStream = null;
                        BufferedReader bufferedReader = null;
                        String data = "";
                        try {
                            Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                            handlerMsg.what = 1;//增加handlerMsg标识符

                            URL url = new URL(Tool.InetAddress + "/setUserInfo.do");//请求地址
                            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                            //连接类相关设置
                            connection.setRequestMethod("POST");
                            connection.setConnectTimeout(3000);//连接服务器超时
                            connection.setReadTimeout(3000);//从服务器读取数据超时
                            connection.setDoInput(true);//允许写入，从服务端读取结果流
                            connection.setDoOutput(true);//允许写出，开启Post请求体
                            connection.setUseCaches(false);//不使用Cache
                            connection.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                            connection.connect();//连接网络
                            String params = "UID=" + application.user.getUID() + "&Uname=" + Uname + "&Upasswd=" + Upasswd + "&Ugender=" + Ugender + "&Uint=" + Uint + "&UfavorPrivacy=" + UfavorPrivacy + "&UcollPrivacy=" + UcollPrivacy;//请求体内容
                            outputStream = connection.getOutputStream();//请求输出流
                            outputStream.write(params.getBytes());

                            int code = connection.getResponseCode();//获得响应状态码
                            if (code == 200) {//返回状态码200，连接成功
                                bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                                data = bufferedReader.readLine();

                                handlerMsg.obj = data;//写入线程传递消息
                            } else handlerMsg.obj = "serverFalse";//服务器通信失败
                            connection.disconnect();//关闭连接

                            handler.sendMessage(handlerMsg);//发送线程消息

                            //若信息修改成功，获取用户信息
                            if (data.equals("updateUserSuccess")) {
                                //发送获取用户信息请求子线程
                                new Thread() {
                                    @Override
                                    public void run() {
                                        OutputStream outputStreamChild = null;
                                        BufferedReader bufferedReaderChild = null;
                                        String dataChild = "";
                                        try {
                                            Message handlerMsgChild = Message.obtain();//构造Message对象，用于向主线程传递消息
                                            handlerMsgChild.what = 2;//增加handlerMsg标识符

                                            URL urlChild = new URL(Tool.InetAddress + "/getUserInfo.do");//请求地址
                                            HttpURLConnection connectionChild = (HttpURLConnection) urlChild.openConnection();

                                            //连接类相关设置
                                            connectionChild.setRequestMethod("POST");
                                            connectionChild.setConnectTimeout(3000);//连接服务器超时
                                            connectionChild.setReadTimeout(3000);//从服务器读取数据超时
                                            connectionChild.setDoInput(true);//允许写入，从服务端读取结果流
                                            connectionChild.setDoOutput(true);//允许写出，开启Post请求体
                                            connectionChild.setUseCaches(false);//不使用Cache
                                            connectionChild.setInstanceFollowRedirects(true);//自动处理重定向，成功获得200状态码
                                            connectionChild.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//设置http请求头格式

                                            connectionChild.connect();//连接网络
                                            String paramsChild = "Uname=" + Uname;//请求体内容
                                            outputStreamChild = connectionChild.getOutputStream();//请求输出流
                                            outputStreamChild.write(paramsChild.getBytes());

                                            int codeChild = connectionChild.getResponseCode();//获得响应状态码
                                            if (codeChild == 200) {//返回状态码200，连接成功
                                                bufferedReaderChild = new BufferedReader(new InputStreamReader(connectionChild.getInputStream()));
                                                dataChild = bufferedReaderChild.readLine();

                                                //解析JSON字符串
                                                JSONArray jsonArray = new JSONArray(dataChild);
                                                User user = new User(
                                                        Integer.parseInt(jsonArray.getJSONObject(0).getString("uid")),
                                                        jsonArray.getJSONObject(0).getString("uname"),
                                                        jsonArray.getJSONObject(0).getString("upasswd"),
                                                        jsonArray.getJSONObject(0).getString("ugender"),
                                                        jsonArray.getJSONObject(0).getString("uint"),
                                                        Integer.parseInt(jsonArray.getJSONObject(0).getString("ufavorPrivacy")),
                                                        Integer.parseInt(jsonArray.getJSONObject(0).getString("ucollPrivacy")),
                                                        Integer.parseInt(jsonArray.getJSONObject(0).getString("ubanLevel")),
                                                        jsonArray.getJSONObject(0).getString("ubanTime")
                                                );

                                                //向Application插入用户信息
                                                application.addUser(user);

                                                handlerMsgChild.obj = dataChild;//写入线程传递消息
                                            } else handlerMsgChild.obj = "serverFalse";//服务器通信失败
                                            connectionChild.disconnect();//关闭连接

                                            handler.sendMessage(handlerMsgChild);//发送线程消息
                                        } catch (IOException e) {
                                            Message handlerMsgChild = Message.obtain();//构造Message对象，用于向主线程传递消息
                                            handlerMsgChild.what = 2;//增加handlerMsg标识符
                                            handlerMsgChild.obj = "serverFalse";
                                            handler.sendMessage(handlerMsgChild);

                                            //throw new RuntimeException(e);
                                        } catch (JSONException e) {
                                            throw new RuntimeException(e);
                                        } finally {
                                            try {
                                                if (bufferedReaderChild != null) bufferedReaderChild.close();
                                                if (outputStreamChild != null) {
                                                    outputStreamChild.flush();
                                                    outputStreamChild.close();
                                                }
                                            } catch (IOException e) {
                                                System.out.println("二级子线程：finally失败");
                                                //throw new RuntimeException(e);
                                            }
                                        }
                                    }
                                }.start();
                            }
                        } catch (IOException e) {
                            Message handlerMsg = Message.obtain();//构造Message对象，用于向主线程传递消息
                            handlerMsg.what = 1;//增加handlerMsg标识符
                            handlerMsg.obj = "serverFalse";
                            handler.sendMessage(handlerMsg);

                            //throw new RuntimeException(e);
                        } finally {
                            try {
                                if (bufferedReader != null) bufferedReader.close();
                                if (outputStream != null) {
                                    outputStream.flush();
                                    outputStream.close();
                                }
                            } catch (IOException e) {
                                System.out.println("子线程：finally失败");
                                //throw new RuntimeException(e);
                            }
                        }
                    }
                }.start();
            }
        });

        //提示弹出框取消按钮监听事件
        buttonSaveSettingCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                relativeLayoutNoticeSetting.setVisibility(View.INVISIBLE);
                relativeLayoutSetting.setVisibility(View.VISIBLE);
                scrollViewSetting.setVisibility(View.VISIBLE);
            }
        });

        //返回图片按钮监听事件
        imageViewSettingBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }

    //Toast消息提示框显示方法
    private void showToast(String s) {
        if (toast == null){
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }else {
            toast.cancel();
            toast = Toast.makeText(this, s, Toast.LENGTH_SHORT);
        }
        toast.show();
    }
}
